/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.requery.ohos.sqlite.demo;

import io.requery.ohos.database.sqlite.SQLiteDatabase;
import io.requery.ohos.database.sqlite.SQLiteOpenHelper;
import ohos.app.Context;

/**
 * SqliteDbHelper
 */
public class SqliteDbHelper extends SQLiteOpenHelper {
    /**
     * DATABASE_NAME
     */
    public static final String DATABASE_NAME = "EmpDatabase.db";

    /**
     * DATABASE_VERSION
     */
    public static final int DATABASE_VERSION = 1;

    private static final String TEXT_TYPE = " TEXT";
    private static final String INTEGER_TYPE = " INTEGER";

    private static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + SqliteContract.SqlEntry.TABLE_NAME + " (" +
                    SqliteContract.SqlEntry.ID + " INTEGER PRIMARY KEY," +
                    SqliteContract.SqlEntry.COLUMN_NAME_EMPNAME + TEXT_TYPE + "," +
                    SqliteContract.SqlEntry.COLUMN_NAME_AGE + INTEGER_TYPE +
                    " )";

    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + SqliteContract.SqlEntry.TABLE_NAME;

    public SqliteDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    private static SqliteDbHelper instance;
    /**
     * onConfigureCalled flag
     */
    public boolean onConfigureCalled = false;

    /**
     * returns instance
     * @param context context
     * @return SqlcipherDbHelper instance
     */
    public static synchronized SqliteDbHelper getInstance(Context context) {
        if (instance == null) {
            instance = new SqliteDbHelper(context);
        }
        return instance;
    }

    /**
     * onCreate
     * @param db The database.
     */


    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }

    /**
     * onUpgrade
     * @param db The database.
     * @param oldVersion The old database version.
     * @param newVersion The new database version.
     */
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }

    /**
     * onConfigure
     * @param database database
     */
    public void onConfigure(SQLiteDatabase database) {
        onConfigureCalled = true;
    }
}
